package com.ip.getip.service.impl;

import com.ip.getip.entity.MailEntity;
import com.ip.getip.util.MailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class MailServiceImpl {

    @Value("${qq.mail.passwd}")
    private String passwd;
    @Value("${qq.mail.accountNumber}")
    private String accountNumber;
    @Value("${qq.mail.makeACopyFor}")
    private List<String> makeACopyFor;
    @Autowired
    MailUtils mailUtils;

    /// 定时获取当前主机IP地址发送给邮件
    // @Scheduled(cron="${task_cron}")
    public void mail() throws Exception {
        String ip = "";
        String chinaz = "http://ip.tool.chinaz.com";
        String inputLine = "";
        String read = "";

        try {
            URL url = new URL(chinaz);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            while ((read = in.readLine()) != null) {
                inputLine += read;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Pattern p = Pattern.compile("\\<dd class=\"fz24\">(.*?)\\<\\/dd>");
        Matcher m = p.matcher(inputLine);
        if (m.find()) {
            ip = m.group(1);
        }
        MailEntity mailEntity = new MailEntity();
        mailEntity.setSender(accountNumber);
        mailEntity.setSenderPass(passwd);
        mailEntity.setAddressees(makeACopyFor);
        mailEntity.setEmailSubject("IP地址");
        mailEntity.setContent("当前IP地址是 :" + ip);
        mailUtils.mailSender(mailEntity);
    }

    // 定时获取当前主机IP地址发送给邮件
    @Scheduled(cron="${task_cron}")
    public void mail2() throws Exception {
        String inputLine = "";
        String read = "";
        URL url = new URL("http://icanhazip.com/");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        while ((read = in.readLine()) != null) {
            inputLine += read;
        }
        MailEntity mailEntity = new MailEntity();
        mailEntity.setSender(accountNumber);
        mailEntity.setSenderPass(passwd);
        mailEntity.setAddressees(makeACopyFor);
        mailEntity.setEmailSubject("IP地址");
        mailEntity.setContent("当前IP地址是 :" + inputLine);
        mailUtils.mailSender(mailEntity);
    }
}
